from django.shortcuts import render, HttpResponse
from utils.tencent.sms import send_sms_single
from django.conf import settings
from django import forms
from demo01 import models
from django.core.validators import RegexValidator


def send_sms(request):
    """发送短信
    请求参数 ?tpl=register  模板ID1
            ?tpl=login  模板ID2
    """
    tpl = request.GET.get('tpl')
    template_id = settings.SMS_TEMPLATE_IDS.get(tpl)
    if not template_id:
        return HttpResponse('短信模板不存在')
    res = send_sms_single('18919713396', template_id, [8888, ])
    print(res)
    if res['result'] == 0:
        return HttpResponse('成功')
    else:
        return HttpResponse(res['errmsg'])


class RegisterModelForm(forms.ModelForm):
    mobile_phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ])
    password = forms.CharField(label='密码', widget=forms.PasswordInput)
    confirm_password = forms.CharField(label='确认密码', widget=forms.PasswordInput)
    code = forms.CharField(label='验证码')

    class Meta:
        model = models.UserInfo
        # 使用__all__ 页面上的表单顺序就是默认安装Model中字段的顺序，再按照自定义forms中的字段顺序
        # fields = "__all__"
        fields = ['username', 'email', 'password', 'confirm_password', 'mobile_phone', 'code']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)


def register(request):
    form = RegisterModelForm()
    return render(request, 'demo01/register.html', {'form': form})
